package com.zjw.controller;

import com.zjw.annotation.domain.ResponseResult;
import com.zjw.annotation.domain.dto.AddRoleDto;
import com.zjw.annotation.domain.dto.ChangeRoleStatusDto;
import com.zjw.annotation.domain.dto.EditRoleDto;
import com.zjw.enums.AppHttpCodeEnum;
import com.zjw.exception.SystemException;
import com.zjw.service.RoleService;
import io.jsonwebtoken.lang.Strings;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/system/role")
@PreAuthorize("@Ps.hasPermission('system:role:list')")
public class RoleController {

    @Autowired
    private RoleService roleService;

    @GetMapping("/list")
    @PreAuthorize("@Ps.hasPermission('system:role:query')")
    public ResponseResult getRoleList(Long pageNum, Long pageSize,
                                      String roleName, String status) {
        return roleService.getRoleList(pageNum, pageSize, roleName, status);
    }


    @PutMapping("/changeStatus")
    @PreAuthorize("@Ps.hasPermission('system:role:edit')")
    public ResponseResult changeRoleStatus(@RequestBody ChangeRoleStatusDto changeRoleStatusDto) {
        return roleService.chanegRoleStatus(changeRoleStatusDto.getRoleId(), changeRoleStatusDto.getStatus());
    }


    @GetMapping("/{id}")
    @PreAuthorize("@Ps.hasPermission('system:role:query')")
    public ResponseResult getRoleById(@PathVariable Long id) {
        return roleService.getRoleById(id);
    }

    @PostMapping
    @PreAuthorize("@Ps.hasPermission('system:role:add')")
    public ResponseResult addRole(@RequestBody AddRoleDto addRoleDto) {
        return roleService.addRole(addRoleDto);
    }


    @PutMapping
    @PreAuthorize("@Ps.hasPermission('system:role:edit')")
    public ResponseResult editRole(@RequestBody EditRoleDto editRoleDto) {
        return roleService.updateRole(editRoleDto);
    }

    @DeleteMapping("/{ids}")
    @PreAuthorize("@Ps.hasPermission('system:role:remove')")
    public ResponseResult removeRole(@PathVariable String ids){
        if(!Strings.hasText(ids))
            throw new SystemException(AppHttpCodeEnum.DATA_UNCOMPLETED);

        List<Long> idList = Arrays.stream(ids.split(",")).map(n -> Long.parseLong(n))
                .collect(Collectors.toList());
        return roleService.removeRole(idList);
    }

    /**
     * 获取所有有效角色 用于后台用户分配角色
     *
     * @return {@link ResponseResult}
     */
    @GetMapping("/listAllRole")
    @PreAuthorize("@Ps.hasPermission('system:role:query')")
    public ResponseResult getAllValidRole(){
        return roleService.getAllValidRole();
    }

}
